"use strict";
var SerialPort = require('serialport');


class Serial {
  constructor() {
    this.name = ""
    this.baudRate = 9600
    this.isok = false
    this.port = false
    this.serialList = []
    this._ondata = function(data){}
  }
  open(name, baudRate){
    this.name = name || this.name
    this.baudRate = parseInt(baudRate) || this.baudRate
    this.port = false
    this.isok = false
    var that = this

    try {
      if (this.name){
        this.port = new SerialPort(this.name, {
          baudRate: this.baudRate
        },function (err) {

          if (err) {
            // console.log('Error: ', err.message)
            that.isok = false
            that.error(err.message)

          }
          that.isok = true

        })

        this.port.on('error', function(err) {
          // console.log('Error: ', err.message);
          that.isok = false
          that.error(err.message)

        })
        this.port.on('close', function() {
          that.isok = false
        })

        this.port.on('data', function (data) {
          // console.log('Data:', data)

          that._ondata(data)
        })

      }

    } catch (e) {
      that.isok = false
      that.error(e)
    }


  }
  stop(){
    try {
      if (this.isok) this.port.close()
    } catch (e) {
      // this.error(e)
    }

  }
  send(msg){
    try {
      if (this.isok){
        // console.log("in send:");
        // console.log(typeof(msg));
        if (typeof(msg)=='string'){
          msg = Buffer.from(msg)
        }
        // console.log("msg",msg);
        this.port.write(msg)
      }
    } catch (e) {
      this.error(e)
    }

  }
  ondata(cb){
    try {
      this._ondata=cb;
    } catch (e) {
      this.error(e)
    }

  }
  update_status(cb){
    var that = this
    setInterval(()=>{
      cb(that.isok,that)
    },100);
  }
  getPorts(callback){
    var that = this
    SerialPort.list(function (err, ports) {
      ports.forEach(function(port) {
        that.serialList.push(port.comName)
      })
      callback(err, ports)
    })
  }
  log(msg){
    console.log(msg);
  }
  error(msg){
    console.error(msg);
  }
  onlog(cb){
    this.log=cb;
  }
  onerror(cb){
    this.error=cb;
  }

}

var serial = new Serial()

module.exports = serial
